/**
 * @file     maxSum.js
 * @brief    [2815. 数组中的最大数对和](https://leetcode.cn/problems/max-pair-sum-in-an-array/)
 * @author   Zhu
 * @date     2024-12-03 16:13
 */

/**
 * @deprecated
 * @param {number[]} nums
 * @return {number}
 */
var maxSum = function (nums) {
    function getMaxBit(num) {
        let max = 0;
        while (num) {
            const bit = num % 10;
            if (bit > max) max = bit;
            num = (num - bit) / 10;
        }
        return max;
    }

    // [51,71,17,24,42]
    // 5  7  7  4   4
    const dict = {};
    for (let i = 0; i < nums.length; i++) {
        const bit = getMaxBit(nums[i]);
        if (dict[bit] == undefined) {
            dict[bit] = [nums[i]];
        } else {
            // 同数位情况下，记录前两个最大元素
            const [a, b] = dict[bit];
            if (!b) {
                if (nums[i] < a) dict[bit] = [a, nums[i]];
                else dict[bit] = [nums[i], a];
            } else if (nums[i] > b && nums[i] < a) {
                dict[bit] = [a, nums[i]];
            } else if (nums[i] >= a) {
                dict[bit] = [nums[i], a];
            }
        }
    }

    let max = -1;
    for (const p in dict) {
        if (dict[p].length === 2) {
            sum = dict[p][0] + dict[p][1];
            if (sum > max) max = sum;
        }
    }

    return max;
};

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSum = function (nums) {
    function getMaxBit(num) {
        let max = 0;
        while (num) {
            const bit = num % 10;
            if (bit > max) max = bit;
            num = (num - bit) / 10;
        }
        return max;
    }

    let ans = -1;
    const max = {};
    for (let i = 0; i < nums.length; i++) {
        const bit = getMaxBit(nums[i]);
        if (max[bit] == undefined) {
            max[bit] = nums[i];
        } else {
            const sum = nums[i] + max[bit];
            if (sum > ans) ans = sum;
            if (nums[i] > max[bit]) {
                max[bit] = nums[i];
            }
        }
    }

    return ans;
};
